#include <stdio.h>
#include <stdlib.h>
#include "timers.h"

void allocateMatrix(int **matr, int hei_a, int wid_a, int randBool);
void malMatrix(int **a, int **b, int wid_a, int hei_a, int wid_b, int **res);
void printMatrix(int **tab, int wid, int hei);
long int recTimer();

main(int argc, char **argv)
{
	long int time_start = recTimer();
	int wid_a, wid_b, hei_a, hei_b;

	if(argc==4) {
		wid_a = (int) strtol(argv[1], NULL, 10);
		hei_a = (int) strtol(argv[2], NULL, 10);
		wid_b = (int) strtol(argv[3], NULL, 10);

	} else {
		wid_a = 100;
		hei_a = 100;
		wid_b = 1;

	}
	hei_b = wid_a;

	int **matrix_a = malloc(sizeof *matrix_a * hei_a);
	int **matrix_b = malloc(sizeof *matrix_b * hei_a);
	int **matrix_res = malloc(sizeof *matrix_res * hei_a);

	unsigned int iseed = (unsigned int)time(NULL);
	srand (iseed);

	int i=0;
	int l;
	if (matrix_a)
	{
		allocateMatrix(matrix_a, hei_a, wid_a, 1);

	}

	if (matrix_b)
	{
		allocateMatrix(matrix_b, hei_b, wid_b, 1);

	}
	if (matrix_res)
	{
		allocateMatrix(matrix_res, hei_a, wid_b, 0);
	}

	//mnozenie
	malMatrix(matrix_a, matrix_b, wid_a, hei_a, wid_b, matrix_res);
	//printMatrix(matrix_res, wid_b, hei_a);
	if(wid_a < 6 && wid_b < 6) {
	printf(" \n ---------------------------------------- \n");
	
	printMatrix(matrix_res, wid_b, hei_a);
	printf(" \n ---------------------------------------- \n");
	}

	printf("Czas całego programu: %f \n", (double)(recTimer()-time_start) / 1000000000);

}

void allocateMatrix(int **matr, int hei_a, int wid_a, int randBool) {
	int i, j;
	for (i = 0; i < hei_a; i++) {
		matr[i] = malloc(sizeof(*matr[i]) * wid_a);

		for (j = 0; j < wid_a; j++) {
			if (randBool) {
				matr[i][j] = rand() / 1000000;
			} else {
				matr[i][j] = 0;
			}
		}

	}

}

void malMatrix(int **a, int **b, int wid_a, int hei_a, int wid_b, int **res) {
	int i, j, k;
	for (i = 0; i < hei_a; i++) {
		for (j = 0; j < wid_b; j++) {
			for (k = 0; k < wid_a; k++) {

				res[i][j] = res[i][j] + (a[i][k] * b[k][j]);
			}
		}
	}

}

void printMatrix(int **tab, int wid, int hei) {
	int i, j;
	for (i = 0; i < hei; i++) {
		for (j = 0; j < wid; j++) {
			printf(" %12d ", tab[i][j]);
		}
		printf("\n");
	}

}
long int recTimer() {
	struct timespec t;
	clock_gettime(CLOCK_MONOTONIC, &t);
	return ((t.tv_sec * TIMER_SCALE) + t.tv_nsec);
}
